import os.path
import sys
import threading
import traceback

from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtWidgets import QMessageBox, QApplication

from ui.ClientUi.Main_ui import MainWindow, load_qss, search_file
from log import logger
from ui.ClientUi.controls.QMessageBoxEx import QMessageBoxEx
from ui.ClientUi.special.login_class import LoginWidget # 登录子界面


# def login_work_thread(main_ui_handle):
#     app = QApplication(sys.argv)  # ui相关初始化，事件循环管理,信号槽机制等
#     print('loginxxxxxxxxxxxx')
#     loginWidget = LoginWidget(target_widget=main_ui_handle)
#     loginWidget.show()
#     sys.exit(app.exec_())

# 适配特定项目
class SpecialMainWindow(MainWindow):
    # special
    showPnSnSignal = pyqtSignal(list)  # 显示pnsn
    showStatusSingal = pyqtSignal(list)  # 显示流程状态
    def __init__(self, engine= None, ui_config = {}, app=None):
        super().__init__(ss=engine)
        # super(MainWindow, self).__init__()
        # self.ss=engine
        self.subDebugWidget = None
        self.ui_config = ui_config
        self.showPnSnSignal.connect(self.showPnSn_slot)
        self.showStatusSingal.connect(self.showStatus_slot) # 显示点检状态等

        if app:
            fn = r'D:\code\git\zxc\project_format_jzbxh\ui\ClientUi\res\styleSheet.qss'
            if not os.path.exists(fn):
                fn = r'D:\code\git\project_format_jzbxh\ui\ClientUi\res\styleSheet.qss'
            SpecialMainWindow.set_qss(app,fn) # 兼容 默认样式
        # is_use_login = True
        is_use_login = False
        # self.showMaximized()
        # self.show()  #

        if is_use_login:
            # login_thread_handle = threading.Thread(target=login_work_thread, args=(self,))
            # login_thread_handle.start()
            self.loginWidget = LoginWidget(target_widget=self)
            # self.loginWidget = LoginWidget()
            self.loginWidget.show()
        else:
            self.showMaximized()
            self.show()  #

        # # 启动即执行点检
        # self.dianjian_slot()

    def showPnSn_slot(self,li):
        scan_str = li[0]
        try:
            # # pn_str, sn_str = scan_str.split(' ') # 格式转换
            # if len(scan_str) < 4:
            #     pn_str = 'PnDefault'
            #     sn_str = 'SnDefault'
            # else:
            #     pn_str = scan_str[:4]
            #     sn_str = scan_str[4:]
            # # DZUPDZUP1SV0003.
            # # DZUP1SV0003.
            # # DZUP1SV0003.
            # # DZUY1SV00055
            pn_str, sn_str = self.ss.sm_handle.get_pnsn()
        except:
           pn_str, sn_str = 'PnDefault','SnDefault'

        self.show_pnsn_label.setText(f'番号: {pn_str}\t线号: {sn_str}')

    def showStatus_slot(self,li):

        # DJ_DICT 2 show_str
        # self.DJ_DICT = {'p_left':
        #                     {'pn_list': ['PnDianJianZong7.5', 'PnDianJianHuang20', 'PnDianJianHuang5', 'PnDianJianHong10', 'PnDianJianLan15','PnDianJianLv30', 'PnDianJianKong'],  # 点检番号顺序
        #                     'res_per_step_list': [],
        #                     'res': -1,
        #                     'status':DJ_Status.NOTEXE,
        #                      'pn_numb': 1,  # 当前番号序号
        #                      # 'step_numb': 1,
        #                     },
        #                 'p_right':
        #                     {'pn_list': ['PnDianJianZong7.5', 'PnDianJianHuang20', 'PnDianJianHuang5', 'PnDianJianHong10', 'PnDianJianLan15','PnDianJianLv30', 'PnDianJianKong'],  # 点检番号顺序
        #                     'res_per_step_list': [],
        #                     'res': -1,
        #                     'status':DJ_Status.NOTEXE,
        #                      'pn_numb': 1,  # 当前番号序号
        #                      # 'step_numb': 1,
        #                     },
        #
        #                 } #
        # class DJ_Status(Enum):  # 点检状态
        #     SUCCESS = 3  # 点检成功
        #     FALSE = 4  # 点检失败
        #     NOTEXE = 5  # 未执行点检
        #     DOING = 6  # 执行点检中
        try:
            DJ_DICT = li[0]
            show_str = ''
            convert_dict = {
                'p_left': '左大保险盒',
                'p_right': '右小保险盒',
                'SUCCESS': '点检成功',
                'FALSE': '点检失败',
                'NOTEXE': '未执行点检',
                'DOING': '执行点检中',

            }
            for service_name, v_dict in DJ_DICT.items():
                if v_dict['status'].name == 'DOING':
                    cur_pn = v_dict['pn_list'][v_dict['pn_numb']-1]
                    show_str += f"{convert_dict[service_name]} {v_dict['pn_numb']}/{len(v_dict['pn_list'])}{convert_dict[v_dict['status'].name]} {cur_pn}\t"
                elif v_dict['status'].name == 'SUCCESS' or v_dict['status'].name == 'FALSE':
                    show_str += f"{convert_dict[service_name]} {len(v_dict['pn_list'])}/{len(v_dict['pn_list'])}{convert_dict[v_dict['status'].name]}\t"

            self.showStatus_label.setText(show_str)
        except:
            print(traceback.format_exc())

    def manual_trigger_slot(self): # 手动触发
        try:
            if not self.subDebugWidget:
                from ui.ClientUi.special.sub_debug_class import SubDebugWidget  # 子界面 手动触发
                self.subDebugWidget = SubDebugWidget(main_ui_handle=self)  # 手动触发界面
            self.subDebugWidget.setWindowModality(Qt.ApplicationModal)  # 设置对话框为模态窗口，防止用户与主窗口交互
            self.subDebugWidget.show()
        except:
            print(traceback.format_exc())

    def dianjian_slot(self): # 点检
        self.loginfo('点击了点检按钮')
        self.loginfo('点检中...')
        # self.ss.DJ_NOTEXE2DJ_DOING()
        self.dianjian_button.setEnabled(False)

    def on_enter_pressed_pn_input_box_slot(self): #
        scan_str = self.pn_input_box.text()
        self.pn_input_box.setText('')
        self.pn_input_box.setPlaceholderText("Enter something and press Enter")
        self.ss.sm_handle.updata_scan_str(scan_str) # pn_str传递给后端
        # try:
        #     pn_str, sn_str = scan_str.split(' ') # 格式转换
        # except:
        #    pn_str, sn_str = '',''
        # self.loginfo(f'当前扫码结果 {scan_str}')
        # self.show_pnsn_label.setText(f'番号: {pn_str}\t线号: {sn_str}')



    def show_fun(self, li): # 同名冲突？
        # print("get single:",data)return
        try:
            service_str, product_str, orig_img, show_img, end, ends, save_img = li
            imgWindowId = self.ui_config['runtime_serviceStep_windowId_dict'][(service_str, product_str)]

            super().show_fun([imgWindowId, orig_img, show_img, end, ends, save_img])

        except:
            logger.info(traceback.format_exc())
        return 0

    @staticmethod
    def set_qss(app,qss_fn=''): #
        load_qss(app,qss_fn)

    # def closeEvent(self, event):
    #     response = QMessageBoxEx.questionEx('退出', '你确定要退出程序吗？', search_file('images\\icon.ico', './'))
    #     if response == QMessageBox.Yes:
    #         # get_config.devcircle[0] = False
    #         # get_config.run_flag[0] = False
    #         self.__IsExitingApp = True
    #         if self.__procCore is not None:
    #             self.__procCore.stop()
    #         if self.__devStatusCheckThread is not None:
    #             self.__devStatusCheckThread.join(1.5)
    #         event.accept()
    #     else:
    #         event.ignore()